package sunyu.tools.dbtools;

import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.generator.DataDictionaryGenerator;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 简易数据库操作工具类
 *
 * @author 孙宇
 */
@Component
public class DbTools {

    private static final String defaultDatabaseName = "main";
    private static final ConcurrentHashMap<String, Dao> daoPoolMap = new ConcurrentHashMap<>();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource(name = "dataSource")
    private DataSource dataSource;

    @PostConstruct
    public void init() {
        addDao(defaultDatabaseName, dataSource);
    }

    @PreDestroy
    public void destroy() {
    }

    public Dao getDao() {
        return daoPoolMap.get(defaultDatabaseName);
    }

    public Dao getDao(String databaseName) {
        return daoPoolMap.get(databaseName);
    }

    public void addDao(String databaseName,
                       DataSource dataSource) {
        logger.info("添加Nutz Dao，名称：{}", databaseName);
        if (daoPoolMap.containsKey(databaseName)) {
            logger.error("{}已存在!", databaseName);
        } else {
            NutDao dao = new NutDao(dataSource);
            dao.setRunner(new SpringDaoRunner());
            daoPoolMap.put(databaseName, dao);
        }
    }

    /**
     * 生成数据库字典
     *
     * @param outputPath 输出目录
     * @param fileName   数据文件名
     */
    public void generatorDatabaseMetaData(String outputPath,
                                          String fileName) {
        logger.info("准备生成TableMeta");
        MetaBuilder metaBuilder = new MetaBuilder(dataSource);
        metaBuilder.setDialect(new MysqlDialect());
        List<TableMeta> tableMetas = metaBuilder.build();
        if (tableMetas.size() == 0) {
            logger.info("TableMeta 数量为 0，不生成任何文件");
            return;
        }

        DataDictionaryGenerator dataDictionaryGenerator = new DataDictionaryGenerator(dataSource, outputPath);
        dataDictionaryGenerator.setDataDictionaryFileName(fileName);
        dataDictionaryGenerator.generate(tableMetas);
        logger.info("TableMeta生成完毕");
    }

}
